package com.demo.gulimall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.demo.gulimall.order.entity.*;
import com.demo.gulimall.order.mapper.MqMessageMapper;
import com.demo.gulimall.order.service.MqMessageService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.IOException;
import java.util.List;

/**
 * @author Chen Yuan
 */

@Service
@RabbitListener(queues = {"hello-java-queue"})
public class MqMessageServiceImpl extends ServiceImpl<MqMessageMapper, MqMessage> implements MqMessageService {

    @Autowired
    private MqMessageMapper mqMessageMapper;


    // 使用 RabbitListener 监听消息, queues:需要监听的队列
    // 参数可以选择的类型: Message、原本的对象、Channel(传输数据的通道)
    //@RabbitListener(queues = {"hello-java-queue"})
    // 将 @RabbitListener 写在类上标注需要监听的队列, @RabbitHandler 写在方法上标注那些方法监听队列, 配合使用重载接收多种类型消息
    @RabbitHandler
    public void testReceiveMessage(Message message, OrderReturnReason content, Channel channel){
        //System.out.println("接收到消息 - message:" + JSON.toJSONString(message));
        //System.out.println("接收到消息 - channel:" + JSON.toJSONString(channel));

        // 当前内通道自增的编号
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 参数: 消息编号, 是否批量确认
        try {
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            // 消息消费异常
            System.out.println("×××消息签收异常 - OrderReturnReason - content:" + JSON.toJSONString(content) + ", deliveryTag:" + deliveryTag);
        }

        System.out.println("接收到消息 - OrderReturnReason - content:" + JSON.toJSONString(content) + ", deliveryTag:" + deliveryTag);
    }
    @RabbitHandler
    public void testReceiveMessage(Order content, Message message, Channel channel){
        // 当前内通道自增的编号
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 签收消息
            // 参数: 消息编号, 是否批量确认
            //channel.basicAck(deliveryTag, false);

            // 拒绝消费, 退回
            // 参数: 消息编号, 是否批量确认, 是否重新入队
            channel.basicNack(deliveryTag, false, true);
        } catch (Exception e) {
            // 消息消费异常
            System.out.println("×××消息签收异常 - Order - content:" + JSON.toJSONString(content) + ", deliveryTag:" + deliveryTag);
        }

        System.out.println("接收到消息 - Order - content:" + JSON.toJSONString(content));
    }
}
